﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Webdiyer.WebControls.Mvc;

namespace MvcWeb.Controllers
{
    public class ManagerSearchController : BaseController
    {
        //
        // GET: /ManagerSearch/

        public ActionResult Index( MvcWeb.ViewModels.Manager.ManagerSearchModel viewModel,int pageindex = 1, int pageSize = 20)
        {
            MvcWeb.ViewModels.Manager.ManagerSearchModel model = new ViewModels.Manager.ManagerSearchModel();
            model.conditionModel = new ViewModels.Manager.ManagerSearchConditonModel();
            
            var iquery = db.AssetManager.AsQueryable();

            if (viewModel != null && viewModel.conditionModel != null)//查询条件
            {
                if (viewModel.conditionModel.AssetCID != -1 && viewModel.conditionModel.AssetCID != null)
                {
                    iquery = iquery.Where(m => m.AssetCID == viewModel.conditionModel.AssetCID);
                }

                if (viewModel.conditionModel.AssetBrand != -1 && viewModel.conditionModel.AssetBrand != null)
                {
                    iquery = iquery.Where(m => m.AssetBrand == viewModel.conditionModel.AssetBrand);
                }

                if (viewModel.conditionModel.AssetSupply != -1 && viewModel.conditionModel.AssetSupply != null)
                {
                    iquery = iquery.Where(m => m.AssetSupply == viewModel.conditionModel.AssetSupply);
                }

                if (viewModel.conditionModel.AssetStatus != -1 && viewModel.conditionModel.AssetStatus != null)
                {
                    iquery = iquery.Where(m => m.AssetStatus == viewModel.conditionModel.AssetStatus);
                }

                if (viewModel.conditionModel.AssetDepartID != -1 && viewModel.conditionModel.AssetDepartID != null)
                {
                    iquery = iquery.Where(m => m.AssetDepartID == viewModel.conditionModel.AssetDepartID);
                }

                if (viewModel.conditionModel.AssetCustodyMemberID != null)
                {
                    iquery = iquery.Where(m => m.AssetCustodyMemberID == viewModel.conditionModel.AssetCustodyMemberID);
                }

                if (viewModel.conditionModel.AssetBarcode !=null && viewModel.conditionModel.AssetBarcode != "")
                {
                    iquery = iquery.Where(m => m.AssetBarcode.Contains( viewModel.conditionModel.AssetBarcode));
                }

                if (viewModel.conditionModel.AssetCustodyAddress != null && viewModel.conditionModel.AssetCustodyAddress != "")
                {
                    iquery = iquery.Where(m => m.AssetCustodyAddress.Contains(viewModel.conditionModel.AssetCustodyAddress));
                }

                if (viewModel.conditionModel.AssetName!=null && viewModel.conditionModel.AssetName != "")
                {
                    iquery = iquery.Where(m => m.AssetName.Contains( viewModel.conditionModel.AssetName));
                }

                if (viewModel.conditionModel.AssetStartBuyTime != null )
                {
                    iquery = iquery.Where(m => m.AssetBuyTime >= viewModel.conditionModel.AssetStartBuyTime);
                }

                if (viewModel.conditionModel.AssetEndBuyTime != null )
                {
                    iquery = iquery.Where(m => m.AssetBuyTime <= viewModel.conditionModel.AssetEndBuyTime);
                }
            }


            iquery = iquery.OrderBy(m => m.AssetID);
            var list = iquery.ToPagedList(pageindex, pageSize);
            model.managerModelList = list;


            var dict = db.AssetCategory.ToList().ToDictionary(a => a.CategoryID, b => b.CategoryName);
            ViewData["categoryCID"] = dict;

            //ViewData["BrandSupplyType"] = new SelectList(MvcWeb.EAMEnum.EAMEnumExt.ToListItem<MvcWeb.EAMEnum.SupplyBrand>(), "value", "text");


            var brandDict = db.AssetBrandSupply.Where(m => (int)m.BrandSupplyType == (int)MvcWeb.EAMEnum.SupplyBrand.品牌商).ToList().ToDictionary(a => a.BrandSupplyID, b => b.BrandSupplyName);
            brandDict.Add(-1, "");
            ViewData["brandDict"] = brandDict;

            var supplyDict = db.AssetBrandSupply.Where(m => (int)m.BrandSupplyType == (int)MvcWeb.EAMEnum.SupplyBrand.供应商).ToList().ToDictionary(a => a.BrandSupplyID, b => b.BrandSupplyName);
            supplyDict.Add(-1, "");
            ViewData["supplyDict"] = supplyDict;

            var brandInfoDict = db.AssetBrandSupply.Where(m => (int)m.BrandSupplyType == (int)MvcWeb.EAMEnum.SupplyBrand.供应商).ToList();
            var brandInfoDictL = brandInfoDict.ToDictionary(a => a.BrandSupplyID, b=>b.BrandSupplyName);
            brandInfoDictL.Add(-1, "");
            ViewData["brandInfoDict"] = brandInfoDictL;
            

            var users = db.aspnet_Users.ToList().ToDictionary(a => a.UserId, b => b.UserName);
            users.Add(new Guid(), "");
            ViewData["AssetCustodyMemberIDDict"] = users;

            var userDepts = db.User_Depts.ToList().ToDictionary(a => a.Id, b => b.Name);
            userDepts.Add(-1, "");
            ViewData["AssetDepartIDDict"] = userDepts;

            var configOtherType = db.AssetConfigOther.ToList();

            var AssetStatus = configOtherType.Where(m => m.AssetConfigType == (int)MvcWeb.EAMEnum.ConfigType.资产状态).ToList().ToDictionary(a => a.AssetConfigID, b => b.AssetConfigName);
            AssetStatus.Add(-1, "");
            ViewData["statusDict"] = AssetStatus;

            
            var assetLevel = configOtherType.Where(m => m.AssetConfigType == (int)MvcWeb.EAMEnum.ConfigType.资产等级).ToList().ToDictionary(a => a.AssetConfigID, b => b.AssetConfigName);
            assetLevel.Add(-1, "");
            ViewData["assetLevelDict"] = assetLevel;

            //var assetLevel = configOtherType.Where(m => m.AssetConfigType == (int)MvcWeb.EAMEnum.ConfigType.资产等级).ToList();
            //AssetStatus.Add(-1, "");
            //ViewData["assetLevelDict"] = assetLevel;

            //AssetOperDict.Add("-1_-1", "请选择");
            //ViewData["StatusOper"] = AssetOperDict;

            //ViewData["StatusOper"] = new SelectList(AssetOperDict, "key", "value");


            //var statusOper = configOtherType.Where(m.AssetConfigType == (int)MvcWeb.EAMEnum.ConfigType.资产等级 || m.AssetConfigType == (int)MvcWeb.EAMEnum.ConfigType.资产使用方式 || m.AssetConfigType == (int)MvcWeb.EAMEnum.ConfigType.借用归还状态).ToList();

            model.assetLevel = -1;
            model.assetStatus = -1;
            return View(model);
        }

        public ActionResult SearchResult(MvcWeb.ViewModels.Manager.ManagerSearchModel viewModel)
        {

            return View();
        }


        //public ActionResult setStatus(string ids, string operVal, string operName)
        //{
        //    string[] idsVal = ids.Split(new Char[] { ',' }, StringSplitOptions.None);
        //    int operValues = int.Parse( (operVal.Split(new Char[] { '_' }, StringSplitOptions.None))[1] );
        //    foreach (string id in idsVal)
        //    {
        //        int aid = int.Parse(id);
        //        EAM.Model.AssetManager model = db.AssetManager.Where(m => m.AssetID == aid).FirstOrDefault();
        //        if (model != null)
        //        {
        //            if (operVal.StartsWith( ((int)MvcWeb.EAMEnum.ConfigType.资产状态).ToString() +"_"))
        //            {
        //                model.AssetStatus = operValues;
        //            }
        //            else if (operVal.StartsWith( ((int)MvcWeb.EAMEnum.ConfigType.资产等级).ToString() + "_"))
        //            {
        //                model.AssetLevel = operValues;
        //            }
        //            db.SaveChanges();
        //        }
        //    }
        //    return View();
        //}

        // GET: /ManagerSearch/setStatus/
        public ActionResult setStatus(string id,string oper)
        {
            //string[] idsOpVal = id.Split(new Char[] { '_' }, StringSplitOptions.None);

            string[] idsVal = id.Split(new Char[] { ',' }, StringSplitOptions.None);
            int operValues = int.Parse(oper);
            foreach (string _id in idsVal)
            {
                int aid = int.Parse(_id);
                EAM.Model.AssetManager model = db.AssetManager.Where(m => m.AssetID == aid).FirstOrDefault();
                if (model != null)
                {
                        model.AssetStatus = operValues;
                    
                    //else if ("2".StartsWith(((int)MvcWeb.EAMEnum.ConfigType.资产等级).ToString() + "_"))
                    //{
                    //    model.AssetLevel = operValues;
                    //}
                    db.SaveChanges();
                }
            }
            return Json(true);
        }

        // GET: /ManagerSearch/setLevel/
        public ActionResult setLevel(string id, string oper)
        {
            //string[] idsOpVal = id.Split(new Char[] { '_' }, StringSplitOptions.None);

            string[] idsVal = id.Split(new Char[] { ',' }, StringSplitOptions.None);
            int operValues = int.Parse(oper);
            foreach (string _id in idsVal)
            {
                int aid = int.Parse(_id);
                EAM.Model.AssetManager model = db.AssetManager.Where(m => m.AssetID == aid).FirstOrDefault();
                if (model != null)
                {
                    model.AssetLevel = operValues;
                    db.SaveChanges();
                }
            }
            return Json(true);
        }

        /// <summary>
        /// 批量修改
        /// </summary>
        // GET: /ManagerSearch/BatchEdit/
        public ActionResult BatchEdit(string id)
        {
            if (id != null && !id.Trim().Equals(""))
            {

                MvcWeb.ViewModels.Manager.ManagerBatchEditModel model = new ViewModels.Manager.ManagerBatchEditModel();

                var iquery = db.AssetManager.AsQueryable();

                int[] i_ids = id.Split(',').Select(m => int.Parse(m)).ToArray();
                iquery = iquery.Where(m => i_ids.Contains(m.AssetID));

                iquery = iquery.OrderBy(m => m.AssetID);
                var list = iquery.ToPagedList(1, 1000);
                model.assetManagerModelList = list;

                model.assetManagerModel = new EAM.Model.AssetManager();

                model.editIDs = id;

                var categoryType = db.AssetCategory.Where(m => m.CategoryParentID == -1 && m.CategoryIsShow == true).ToList().ToDictionary(a => a.CategoryID, b => b.CategoryName);
                ViewData["categoryTypeList"] = categoryType;

                //var childCategoryType = db.AssetCategory.Where(m => m.CategoryParentID == cid && m.CategoryIsShow == true).ToList().ToDictionary(a => a.CategoryID, b => b.CategoryName);//子类型

                var brandSupply = db.AssetBrandSupply.ToList();//供应商 品牌商
                var supplyList = brandSupply.Where(m => m.BrandSupplyType == (int)MvcWeb.EAMEnum.SupplyBrand.供应商).ToList().ToDictionary(a => a.BrandSupplyID, b => b.BrandSupplyName);
                var brandList = brandSupply.Where(m => m.BrandSupplyType == (int)MvcWeb.EAMEnum.SupplyBrand.品牌商).ToList().ToDictionary(a => a.BrandSupplyID, b => b.BrandSupplyName);
                ViewData["brandList"] = brandList;
                ViewData["supplyList"] = supplyList;

                var userDepts = db.User_Depts.ToList().ToDictionary(a => a.Id, b => b.Name);//部门
                ViewData["AssetDepartIDList"] = userDepts;

                var users = db.aspnet_Users.ToList().ToDictionary(a => a.UserId, b => b.UserName);//用户信息
                ViewData["AssetCustodyMemberIDList"] = users;
                ViewData["AssetUsedMemberIDList"] = users;
                ViewData["AssetPurchaseIDList"] = users;

                var configType = db.AssetConfigOther.ToList();//配置信息
                var manLevel = configType.Where(m => m.AssetConfigType == (int)MvcWeb.EAMEnum.ConfigType.资产等级).ToList().ToDictionary(a => a.AssetConfigID, b => b.AssetConfigName);
                ViewData["AssetLevelList"] = manLevel;

                var purchaseCostFromLevel = configType.Where(m => m.AssetConfigType == (int)MvcWeb.EAMEnum.ConfigType.资金来源).ToList().ToDictionary(a => a.AssetConfigID, b => b.AssetConfigName);
                ViewData["AssetPurchaseCostFromList"] = purchaseCostFromLevel;


                var fromLevel = configType.Where(m => m.AssetConfigType == (int)MvcWeb.EAMEnum.ConfigType.资产增加来源).ToList().ToDictionary(a => a.AssetConfigID, b => b.AssetConfigName);
                ViewData["AssetFromList"] = fromLevel;


                var AssetOut = configType.Where(m => m.AssetConfigType == (int)MvcWeb.EAMEnum.ConfigType.资产减少去处).ToList().ToDictionary(a => a.AssetConfigID, b => b.AssetConfigName);
                ViewData["AssetOutList"] = AssetOut;

                var AssetStatus = configType.Where(m => m.AssetConfigType == (int)MvcWeb.EAMEnum.ConfigType.资产状态).ToList().ToDictionary(a => a.AssetConfigID, b => b.AssetConfigName);
                ViewData["AssetStatusList"] = AssetStatus;

                return View(model);
            }
            else
            {
                return View();
            }
        }


        [HttpPost]
        public ActionResult BatchEdit(MvcWeb.ViewModels.Manager.ManagerBatchEditModel viewModel)
        {
            var user = System.Web.Security.Membership.GetUser();
            var guid = (Guid)user.ProviderUserKey;
            
            string ids = viewModel.editIDs;
            string[] idArray = ids.Split(new Char[]{','}, StringSplitOptions.None);
            foreach (string _id in idArray)
            {
                int id = int.Parse(_id);

                var model = db.AssetManager.Find(id);
                db.AssetManager.Attach(model);

                //model.AssetCID = viewModel.assetManagerModel.AssetCID ;
                if (viewModel.assetManagerModel.AssetBrand != null)
                    model.AssetBrand = viewModel.assetManagerModel.AssetBrand;

                if (viewModel.assetManagerModel.AssetBarcode != null)
                    model.AssetBarcode = viewModel.assetManagerModel.AssetBarcode;

                if (viewModel.assetManagerModel.AssetStatus != null)
                    model.AssetStatus = viewModel.assetManagerModel.AssetStatus;

                if (viewModel.assetManagerModel.AssetSupply != null)
                    model.AssetSupply = viewModel.assetManagerModel.AssetSupply;
                if (viewModel.assetManagerModel.AssetContractID != null)
                    model.AssetContractID = viewModel.assetManagerModel.AssetContractID;
                if (viewModel.assetManagerModel.AssetCustodyMemberID != null)
                    model.AssetPurchaseID = viewModel.assetManagerModel.AssetPurchaseID;
                if (viewModel.assetManagerModel.AssetPurchaseName != null)
                    model.AssetPurchaseName = viewModel.assetManagerModel.AssetPurchaseName;
                if (viewModel.assetManagerModel.AssetPurchaseCost != null)
                    model.AssetPurchaseCost = viewModel.assetManagerModel.AssetPurchaseCost;
                if (viewModel.assetManagerModel.AssetPurchaseCostFrom != null)
                    model.AssetPurchaseCostFrom = viewModel.assetManagerModel.AssetPurchaseCostFrom;
                if (viewModel.assetManagerModel.AssetPurchaseTime != null)
                    model.AssetPurchaseTime = viewModel.assetManagerModel.AssetPurchaseTime;
                if (viewModel.assetManagerModel.AssetFrom != null)
                    model.AssetFrom = viewModel.assetManagerModel.AssetFrom;
                if (viewModel.assetManagerModel.AssetOut != null)
                    model.AssetOut = viewModel.assetManagerModel.AssetOut;
                if (viewModel.assetManagerModel.AssetOutManu != null)
                    model.AssetOutManu = viewModel.assetManagerModel.AssetOutManu;
                if (viewModel.assetManagerModel.AssetCustodyAddress != null)
                    model.AssetCustodyAddress = viewModel.assetManagerModel.AssetCustodyAddress;
                if (viewModel.assetManagerModel.AssetCustodyMemberID != null)
                    model.AssetCustodyMemberID = viewModel.assetManagerModel.AssetCustodyMemberID;
                if (viewModel.assetManagerModel.AssetCustodyMemberName != null)
                    model.AssetCustodyMemberName = viewModel.assetManagerModel.AssetCustodyMemberName;
                if (viewModel.assetManagerModel.AssetCustodyMemberID != null)
                    model.AssetUsedMemberID = viewModel.assetManagerModel.AssetUsedMemberID;
                if (viewModel.assetManagerModel.AssetUsedMemberName != null)
                    model.AssetUsedMemberName = viewModel.assetManagerModel.AssetUsedMemberName;
                if (viewModel.assetManagerModel.AssetUsedAddress != null)
                    model.AssetUsedAddress = viewModel.assetManagerModel.AssetUsedAddress;
                if (viewModel.assetManagerModel.AssetUsedYear != null)
                    model.AssetUsedYear = viewModel.assetManagerModel.AssetUsedYear;
                if (viewModel.assetManagerModel.AssetDepriciationRate != null)
                    model.AssetDepriciationRate = viewModel.assetManagerModel.AssetDepriciationRate;
                if (viewModel.assetManagerModel.AssetDepartID != null)
                    model.AssetDepartID = viewModel.assetManagerModel.AssetDepartID;
                if (viewModel.assetManagerModel.AssetDepartName != null)
                    model.AssetDepartName = viewModel.assetManagerModel.AssetDepartName;
                if (viewModel.assetManagerModel.AssetDescript != null)
                    model.AssetDescript = viewModel.assetManagerModel.AssetDescript;
                if (viewModel.assetManagerModel.AssetLevel != null)
                    model.AssetLevel = viewModel.assetManagerModel.AssetLevel;
                if (viewModel.assetManagerModel.AssetBuyCode != null)
                    model.AssetBuyCode = viewModel.assetManagerModel.AssetBuyCode;
                if (viewModel.assetManagerModel.AssetBuysssInvoiceNumber != null)
                    model.AssetBuysssInvoiceNumber = viewModel.assetManagerModel.AssetBuysssInvoiceNumber;
                if (viewModel.assetManagerModel.AssetBuyTime != null)
                    model.AssetBuyTime = viewModel.assetManagerModel.AssetBuyTime;
                if (viewModel.assetManagerModel.AssetSpecModel != null)
                    model.AssetSpecModel = viewModel.assetManagerModel.AssetSpecModel;

                if (viewModel.assetManagerModel.AssetMaintenanCycle != null)
                    model.AssetMaintenanCycle = viewModel.assetManagerModel.AssetMaintenanCycle;
                model.AssetLastUpdateMember = guid;
                model.AssetLastUpdateTime = DateTime.Now;
                if (viewModel.assetManagerModel.AssetWarrant != null)
                    model.AssetWarrant = viewModel.assetManagerModel.AssetWarrant;
                if (viewModel.assetManagerModel.AssetWarrantLastTime != null)
                    model.AssetWarrantLastTime = viewModel.assetManagerModel.AssetWarrantLastTime;

                db.SaveChanges();
            }
            return RedirectToAction("Index");
        }

        /// <summary>
        /// 批量合并
        /// </summary>
        // GET: /ManagerSearch/BatchMerger/
        public ActionResult BatchMerger(string id)
        {

            var user = System.Web.Security.Membership.GetUser();
            var guid = (Guid)user.ProviderUserKey;
            
            string[] idArray = id.Split(new Char[]{','}, StringSplitOptions.None);
            string mergerLabel = "该资产由:";
            EAM.Model.AssetManager newModel = db.AssetManager.Find(int.Parse(idArray[0]));
            db.AssetManager.Add(newModel);
            db.SaveChanges();


            foreach (string _id in idArray)
            {
                int innerid = int.Parse(_id);

                var model = db.AssetManager.Find(innerid);
                 
                db.AssetManager.Attach(model);
                model.AssetStatus = 4;
                model.AssetLastUpdateMember = guid;
                model.AssetLastUpdateTime = DateTime.Now;
                newModel.AssetPurchaseCost = newModel.AssetPurchaseCost + model.AssetPurchaseCost;

                mergerLabel += "," + model.AssetLabel;

                db.SaveChanges();
            }
            mergerLabel += " 合并而成";
            newModel.AssetDescript = mergerLabel;
            db.SaveChanges();
            return RedirectToAction("index");
        }

    }
}
